using DeviceCommons.DataHandling;
using DeviceCommons.DataHandling.Compression;
using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Factories;
using DeviceCommons.DeviceMessages.Serialization;
using DeviceCommons.Security;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

namespace DeviceCommons
{
    /// <summary>
    /// DeviceCommons依赖注入扩展方法
    /// </summary>
    public static class DeviceCommonsServiceCollectionExtensions
    {
        /// <summary>
        /// 注册DeviceCommons核心服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureOptions">配置选项</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddDeviceCommons(
            this IServiceCollection services,
            Action<DeviceCommonsOptions>? configureOptions = null)
        {
            // 注册配置选项（使用IOptions模式）
            services.AddOptions<DeviceCommonsOptions>();
            if (configureOptions != null)
            {
                services.Configure(configureOptions);
            }

            // 注册核心服务
            RegisterCoreServices(services);

            // 注册序列化服务
            RegisterSerializationServices(services);

            // 注册安全服务
            RegisterSecurityServices(services);

            // 注册工厂服务
            RegisterFactoryServices(services);

            // 注册配置验证服务
            RegisterConfigurationServices(services);

            return services;
        }

        /// <summary>
        /// 注册自定义状态工厂
        /// </summary>
        /// <typeparam name="TFactory">工厂类型</typeparam>
        /// <param name="services">服务集合</param>
        /// <param name="deviceType">设备类型</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddStateFactory<TFactory>(
            this IServiceCollection services,
            byte deviceType)
            where TFactory : class, IStateFactory
        {
            services.TryAddTransient<TFactory>();

            // 注册工厂到StateFactoryRegistry
            var registration = new StateFactoryRegistration(deviceType, typeof(TFactory));
            services.TryAddSingleton(registration);

            return services;
        }

        /// <summary>
        /// 使用AES加密
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="password">加密密码</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithAesEncryption(
            this IServiceCollection services,
            string password) => WithDefaultAesEncryption(services, password);

        /// <summary>
        /// 使用默认AES加密
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="password">加密密码</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithDefaultAesEncryption(
            this IServiceCollection services,
            string password)
        {
            services.Configure<DeviceCommonsOptions>(options =>
            {
                options.DefaultEncryptionPassword = password;
                options.EnableDefaultAesEncryption = true;
                // 默认使用快速模式，保持向后兼容
                options.AesEncryptionMode = AesMode.Fast;
            });

            return services;
        }
        
        /// <summary>
        /// 使用默认AES加密，并指定加密模式
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="password">加密密码</param>
        /// <param name="mode">AES加密模式（快速模式或安全模式）</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithDefaultAesEncryption(
            this IServiceCollection services,
            string password,
            AesMode mode)
        {
            services.Configure<DeviceCommonsOptions>(options =>
            {
                options.DefaultEncryptionPassword = password;
                options.EnableDefaultAesEncryption = true;
                options.AesEncryptionMode = mode;
            });

            return services;
        }
        
        /// <summary>
        /// 使用AES快速模式加密（1000次PBKDF2迭代，启用缓存）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="password">加密密码</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithFastAesEncryption(
            this IServiceCollection services,
            string password) => WithDefaultAesEncryption(services, password, AesMode.Fast);
            
        /// <summary>
        /// 使用AES安全模式加密（60000次PBKDF2迭代，禁用缓存）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="password">加密密码</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithSecureAesEncryption(
            this IServiceCollection services,
            string password) => WithDefaultAesEncryption(services, password, AesMode.Secure);

        /// <summary>
        /// 使用GZIP压缩
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns></returns>
        public static IServiceCollection WithGZipCompression(
            this IServiceCollection services) => WithDefaultGZipCompression(services);

        /// <summary>
        /// 使用默认GZIP压缩
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithDefaultGZipCompression(
            this IServiceCollection services)
        {
            services.Configure<DeviceCommonsOptions>(options =>
            {
                options.EnableDefaultGZipCompression = true;
            });

            return services;
        }

        /// <summary>
        /// 配置自定义加密解密函数
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="encryptFunc">加密函数</param>
        /// <param name="decryptFunc">解密函数</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection WithCustomEncryption(
            this IServiceCollection services,
            Func<string, string>? encryptFunc = null,
            Func<string, string>? decryptFunc = null)
        {
            services.Configure<DeviceCommonsOptions>(options =>
            {
                options.EncryptFunc = encryptFunc;
                options.DecryptFunc = decryptFunc;
            });

            return services;
        }

        public static IServiceCollection WithCustomCompression(
            this IServiceCollection services,
            Func<byte[], byte[]>? compressFunc = null,
            Func<byte[], byte[]>? decompressFunc = null)
        {
            services.Configure<DeviceCommonsOptions>(options =>
            {
                options.CompressFunc = compressFunc;
                options.DecompressFunc = decompressFunc;
            });

            return services;
        }

        private static void RegisterCoreServices(IServiceCollection services)
        {
            // 注册构建器
            services.TryAddTransient<IDeviceMessageBuilder, DeviceMessageBuilder>();

            // 注册工具类
            services.TryAddSingleton<DeviceMessageUtilities>();
            services.TryAddSingleton<DeviceMessageArrayPool>();

            // 注册序列化器提供服务
            services.TryAddSingleton<IDeviceMessageSerializerProviderService, DeviceMessageSerializerProviderService>();
        }

        private static void RegisterSerializationServices(IServiceCollection services)
        {
            // 注册序列化器
            services.TryAddSingleton<IDeviceMessageSerializer, DeviceMessageSerializer>();
            services.TryAddSingleton<IDeviceMessageParser, DeviceMessageParser>();
            services.TryAddSingleton<IDeviceMessageHeaderParser, DeviceMessageHeaderParser>();

            // 注册版本特定的序列化器和解析器
            RegisterV1Services(services);
            RegisterV2Services(services);
        }

        private static void RegisterV1Services(IServiceCollection services)
        {
            // V1 序列化器
            services.TryAddSingleton<DeviceMessages.Serialization.V1.Serializers.IDeviceMessageHeaderSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageHeaderSerializer>();
            services.TryAddSingleton<IDeviceMessageInfoSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageInfoSerializer>();
            services.TryAddSingleton<IDeviceMessageInfoReadingsSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageInfoReadingsSerializer>();
            services.TryAddSingleton<IDeviceMessageInfoReadingSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageInfoReadingSerializer>();
            services.TryAddSingleton<IDeviceMessageInfoReadingStatesSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageInfoReadingStatesSerializer>();
            services.TryAddSingleton<IDeviceMessageInfoReadingStateSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageInfoReadingStateSerializer>();
            services.TryAddSingleton<IDeviceMessageChildSerializer,
                DeviceMessages.Serialization.V1.Serializers.DeviceMessageChildSerializer>();

            // V1 解析器
            services.TryAddSingleton<IDeviceMessageInfoParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageInfoParser>();
            services.TryAddSingleton<IDeviceMessageInfoReadingsParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageInfoReadingsParser>();
            services.TryAddSingleton<IDeviceMessageInfoReadingParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageInfoReadingParser>();
            services.TryAddSingleton<IDeviceMessageInfoReadingStatesParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageInfoReadingStatesParser>();
            services.TryAddSingleton<IDeviceMessageInfoReadingStateParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageInfoReadingStateParser>();
            services.TryAddSingleton<IDeviceMessageChildParser,
                DeviceMessages.Serialization.V1.Parsers.DeviceMessageChildParser>();
        }

        private static void RegisterV2Services(IServiceCollection services)
        {
            // V2 序列化器
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageHeaderSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageInfoSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageInfoReadingsSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageInfoReadingSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageInfoReadingStatesSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageInfoReadingStateSerializer>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Serializers.DeviceMessageChildSerializer>();

            // V2 解析器
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageInfoParser>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageInfoReadingsParser>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageInfoReadingParser>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageInfoReadingStatesParser>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageInfoReadingStateParser>();
            services.TryAddSingleton<DeviceMessages.Serialization.V2.Parsers.DeviceMessageChildParser>();
        }

        private static void RegisterSecurityServices(IServiceCollection services)
        {
            services.TryAddSingleton<CrcCalculator>();
            services.TryAddSingleton<AesEncryptor>();
            services.TryAddSingleton<Compressor>(); // 添加这行
        }

        private static void RegisterFactoryServices(IServiceCollection services)
        {
            // 注册默认状态工厂
            services.TryAddSingleton<IStateFactory, DefaultStateFactory>();

            // 注册状态工厂注册中心服务
            services.TryAddSingleton<IStateFactoryRegistry, StateFactoryRegistryService>();
        }

        private static void RegisterConfigurationServices(IServiceCollection services)
        {
            // 注册配置验证和应用服务
            services.TryAddSingleton<IDeviceCommonsConfigurationService, DeviceCommonsConfigurationService>();
        }
    }

    /// <summary>
    /// 状态工厂注册信息
    /// </summary>
    public class StateFactoryRegistration
    {
        public byte DeviceType { get; }
        public Type FactoryType { get; }

        public StateFactoryRegistration(byte deviceType, Type factoryType)
        {
            DeviceType = deviceType;
            FactoryType = factoryType;
        }
    }
}